const version = 1;
const CACHE_NAME = "cache_v" + version;
const staticFiles = [
    '/',
    '/index.html',
    '/css/index.css',
    '/js/index.js',
    '/assets/fonts/graduate.eot',
    '/assets/fonts/graduate.ttf',
    '/assets/fonts/graduate.woff',
    '/assets/images/icon128.png',
    '/assets/images/icon144.png',
];

/**
 * service worker 安装
 */
self.addEventListener('install', (event) => {
    console.log('install 成功', event);

    // 这里一般静态资源的预缓存
    // self.skipWaiting 可以阻止等待，让新service worker安装成功后立即激活。
    event.waitUntil(
        caches.open(CACHE_NAME).then(cache => {
            return cache.addAll(staticFiles);
        }).then(self.skipWaiting)
    );
});

/**
 * service worker 激活
 */
self.addEventListener('activate', (event) => {
    console.log('activate 成功', event);

    // 删除旧的缓存
    // 所有客户端获取控制权
    event.waitUntil(
        Promise.all([
            self.clients.claim(),
            caches.keys().then(keys => {
                keys.forEach(key => {
                    if (CACHE_NAME !== key) {
                        caches.delete(key);
                    }
                });
            })
        ])
    );
})

function saveToCache(req, res) {
    return caches
        .open(CACHE_NAME)
        .then(cache => cache.put(req, res));
}

self.addEventListener('fetch', (event) => {
    const req = event.request;

    // 拦截请求，并利用fetch api 和 cache api把结果给到event.respondWith() 即可实现离线缓存
    event.respondWith(
        fetch(req).then((response) => {
            saveToCache(req, response.clone());
            return response;
        }).catch(error => {
            return caches.open(CACHE_NAME).then(cache => {
                return cache.match(req);
            })
        }));
});